<template>
  <base-content>
    <template>
      <el-form ref="form" :model="form" label-width="180px">
        <el-form-item v-if="isDisabled" label="商品ID">
          <el-col :span="4">{{ form.product_id }}</el-col>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-col :span="4">
            <el-select v-model="form.product_id" filterable :disabled="id !== ''" placeholder="请选择商品名称" @change="selectProduct">
              <el-option v-for="(prod, pIndex) in productList" :key="pIndex" :label="productText(prod)" :value="prod.id" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="拼团价格">
          <el-col :span="4">
            <el-input v-model="form.collage_price" type="number" :disabled="id !== ''" placeholder="请输入商品拼团价格" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品原价">{{ product.price || '-' }}</el-form-item>
        <el-form-item label="正常售卖价">{{ product.price_discount || '-' }}</el-form-item>
        <el-form-item label="商品类型">{{ product.product_type === 1 ? '商品' : product.product_type === 2 ? '服务' : '-' }}</el-form-item>
        <el-form-item label="商品规格">{{ product.product_attribute || '-' }}</el-form-item>
        <el-form-item label="商品提供方">{{ product.provider_dept_name || '-' }}</el-form-item>
        <el-form-item label="可拼团范围">
          <el-col :span="4">
            <rm-tree-select
              ref="wl-tree-select"
              v-model="form.dept_id"
              check-on-click-node
              node-key="id"
              width="240"
              checkbox
              no-checked-close
              :data="treeData"
              :default-expand-all="false"
              :default-expanded-keys="[1]"
              @change="scopeSelectChange"
            />
            <p>不选任意值，全平台可售卖，首页推荐范围内</p>
          </el-col>
        </el-form-item>
        <el-form-item label="库存">
          <el-col :span="4">
            <el-input v-model="form.quantity" type="number" placeholder="请输入库存" />
          </el-col>
        </el-form-item>
        <el-form-item label="参与人数上限">
          <el-col :span="4">
            <el-input-number v-model="form.max_people" :disabled="id !== ''" :max="5" placeholder="请输入参与人数上限" />
          </el-col></el-form-item>
        <el-form-item label="成功购买人数">
          <el-col :span="4">
            <el-input-number v-model="form.success_people" :disabled="id !== ''" :max="5" placeholder="请输入成功购买人数" />
          </el-col></el-form-item>
        <el-form-item label="平台分成（积分）">
          <el-col :span="4">
            <el-select v-model="form.collage_rate_list[0].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.collage_rate_list[0].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="运营中心分成（积分）">
          <el-col :span="4">
            <el-select v-model="form.collage_rate_list[1].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.collage_rate_list[1].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="咨询中心分成（积分）">
          <el-col :span="4">
            <el-select v-model="form.collage_rate_list[2].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.collage_rate_list[2].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="提供商分成（积分）">
          <el-col :span="4">
            <el-select v-model="form.collage_rate_list[3].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.collage_rate_list[3].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="推荐者分成（积分）">
          <el-col :span="4">
            <el-select v-model="form.collage_rate_list[4].rate_type" placeholder="请选择分成类型">
              <el-option label="数字" :value="1" />
              <el-option label="百分比" :value="2" />
            </el-select>
          </el-col>
          <el-col style="text-align: center" :span="1">-</el-col>
          <el-col :span="4">
            <el-input v-model="form.collage_rate_list[4].rate_value" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="未购买补偿">
          <el-col :span="4">
            <el-select v-model="form.coupon_id" placeholder="请选择优惠券" @change="selectCoupon">
              <el-option v-for="(coup, cIndex) in couponList" :key="cIndex" :label="coup.coupon_name" :value="coup.id" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="拼团状态">
          <el-col :span="4">
            <el-select v-model="form.collage_status" placeholder="请选择拼团状态">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="2" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保  存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
  </base-content>
</template>

<script>
import { getDeptList } from '@/api/production-api'
import { getAllProducts, getAllCoupon, createCollage, getCollageDetail, updateCollage } from '@/api/groupbuy'
import RmTreeSelect from '@/components/sl-tree.vue'

export default {
  components: { RmTreeSelect },
  data() {
    return {
      isDisabled: false,
      treeData: [
        {
          id: '0',
          name: '所有平台',
          children: []
        }
      ],
      productList: [],
      couponList: [],
      product: {},
      coupon: {},
      id: '',
      form: {
        collage_rate_list: [
          { rate_type: '', rate_value: '', role_type: 1 },
          { rate_type: '', rate_value: '', role_type: 2 },
          { rate_type: '', rate_value: '', role_type: 3 },
          { rate_type: '', rate_value: '', role_type: 4 },
          { rate_type: '', rate_value: '', role_type: 5 }
        ],
        dept_id: [],
        product_id: '',
        collage_price: '',
        quantity: '',
        max_people: '',
        success_people: '',
        coupon_id: '',
        collage_status: '',
        pageSize: 10,
        pageNum: 1
      }
    }
  },
  async created() {
    const result = await getDeptList()
    if (result.code === '0') {
      const list = result.info.data
      this.selsAreas = result.info.data
      // 初始化第一层数据
      const treeList = list.filter((item) => item.dept_parent_id === 0)
      const trees = []
      treeList.forEach((item) => {
        const arr = this.toTreeData(list, item.id)
        trees.push({ id: item.id, name: item.dept_name, children: arr })
      })
      this.treeData[0].children = trees
    } else {
      this.selsAreas = []
    }
  },
  mounted() {
    // 商品列表
    this.queryProducts()
    // 优惠券列表
    this.queryCoupons()
    const query = this.$route.query
    // 详情接口
    if (query && query.id) {
      this.id = query.id
      this.queryDetail(query.id)
    }
  },
  methods: {
    // 拼团详情
    async queryDetail(id) {
      const result = await getCollageDetail({ id })
      if (result.code === '0') {
        const entity = result.info.data
        this.form = entity
        const product = this.productList.filter((item) => item.id === entity.product_id)[0]
        this.product = product
      }
    },
    // 商品列表查询
    async queryProducts() {
      const result = await getAllProducts({ status: 1, page_size: this.pageSize, page_num: this.pageNum })
      if (result.code === '0') {
        this.productList = result.info.data
      }
    },
    // 优惠券列表查询
    async queryCoupons() {
      const result = await getAllCoupon({ coupon_use_type: [0, 1], is_enabled: 1 })
      if (result.code === '0') {
        this.couponList = result.info.data
      }
    },
    // 拼接商品名称展示
    productText(prod) {
      return `${prod.id}-${prod.product_name}`
    },
    toTreeData(data, pid) {
      function tree(id) {
        const arr = []
        data.filter(item => {
          return item.dept_parent_id === id
        }).forEach(item => {
          arr.push({
            id: item.id,
            name: item.dept_name,
            children: tree(item.id)
          })
        })
        return arr
      }
      // 第一级节点的父id，是null或者0，视情况传入
      return tree(pid)
    },
    // 选择商品 下拉
    selectProduct(val) {
      this.product = this.productList.filter((item) => item.id === val)[0]
      this.form.product_id = val
    },
    // 选择优惠券 下拉
    selectCoupon(val) {
      this.coupon = this.couponList.filter((item) => item.id === val)[0]
      this.form.coupon_id = val
    },
    // 保存
    async onSubmit() {
      const param = this.form
      param.collage_price = Number(param.collage_price)
      param.quantity = Number(param.quantity)
      const numberValue = /^[0-9]+$/
      const floatValue = /^(\d+)(.\d{0,2})?$/
      if (!param.product_id) {
        return this.$message.error('请选择一个商品')
      }
      if (!param.collage_price || param.collage_price === 0) {
        return this.$message.error('请输入商品拼团价格')
      }
      if (!floatValue.test(param.collage_price)) {
        return this.$message.error('请输入正确拼团商品价格，最多保留两位小数')
      }
      if (Number(param.max_people) === 0) {
        return this.$message.error('参与人数上限不能为零')
      }
      if (Number(param.success_people === 0)) {
        return this.$message.error('成功购买人数不能为零')
      }
      if (param.success_people > param.max_people) {
        return this.$message.error('成功购买人数不能大于参与人数上限')
      }
      if (param.collage_rate_list[0].rate_type === '') {
        return this.$message.error('请选择平台分成类型')
      }
      if (param.collage_rate_list[0].rate_type === 1 && !numberValue.test(param.collage_rate_list[0].rate_value)) {
        return this.$message.error('平台分成只输入正整数')
      }
      if (param.collage_rate_list[0].rate_type === 2 && !floatValue.test(param.collage_rate_list[0].rate_value)) {
        return this.$message.error('平台分成数字格式错误，最多保留两位小数')
      }
      if (param.collage_rate_list[1].rate_type === '') {
        return this.$message.error('请选择运营中心类型')
      }
      if (param.collage_rate_list[1].rate_type === 1 && !numberValue.test(param.collage_rate_list[1].rate_value)) {
        return this.$message.error('运营中心分成只输入正整数')
      }
      if (param.collage_rate_list[1].rate_type === 2 && !floatValue.test(param.collage_rate_list[1].rate_value)) {
        return this.$message.error('运营中心分成数字格式错误，最多保留两位小数')
      }
      if (param.collage_rate_list[2].rate_type === '') {
        return this.$message.error('请选择咨询中心分成类型')
      }
      if (param.collage_rate_list[2].rate_type === 1 && !numberValue.test(param.collage_rate_list[2].rate_value)) {
        return this.$message.error('咨询中心分成只输入正整数')
      }
      if (param.collage_rate_list[2].rate_type === 2 && !floatValue.test(param.collage_rate_list[2].rate_value)) {
        return this.$message.error('咨询中心分成数字格式错误，最多保留两位小数')
      }
      if (param.collage_rate_list[3].rate_type === '') {
        return this.$message.error('请选择提供商分成类型')
      }
      if (param.collage_rate_list[3].rate_type === 1 && !numberValue.test(param.collage_rate_list[3].rate_value)) {
        return this.$message.error('提供商分成只输入正整数')
      }
      if (param.collage_rate_list[3].rate_type === 2 && !floatValue.test(param.collage_rate_list[3].rate_value)) {
        return this.$message.error('提供商分成数字格式错误，最多保留两位小数')
      }
      if (param.collage_rate_list[4].rate_type === '') {
        return this.$message.error('请选择推荐者分成类型')
      }
      if (param.collage_rate_list[4].rate_type === 1 && !numberValue.test(param.collage_rate_list[4].rate_value)) {
        return this.$message.error('推荐者分成只输入正整数')
      }
      if (param.collage_rate_list[4].rate_type === 2 && !floatValue.test(param.collage_rate_list[4].rate_value)) {
        return this.$message.error('推荐者分成数字格式错误，最多保留两位小数')
      }
      if (!param.coupon_id) {
        return this.$message.error('请选择未购买补偿优惠券')
      }
      if (!param.collage_status) {
        return this.$message.error('请选择拼团状态')
      }
      let result = {}
      if (this.id) {
        param.id = this.id
        result = await updateCollage(param)
      } else {
        result = await createCollage(param)
      }
      if (result.code === '0') {
        this.$message.success('保存成功')
        this.cancel()
      } else {
        this.$message.error(`保存失败：${result.msg}`)
      }
    },
    // 取消
    cancel() {
      this.$router.push('/groupbuy/list')
    },
    // 监听 可售卖范围改变
    scopeSelectChange(val) {
      const scopeIds = val.map((item) => item.id)
      this.form.dept_id = scopeIds
    }
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
